<script setup>
import { ref, onMounted, computed } from 'vue'
import { Search, Plus, Edit, Delete } from '@element-plus/icons-vue'
import { useProductStore } from '@/stores/productStore'
import AlertNotification from '@/components/AlertNotification.vue'

const productStore = useProductStore()
const alertRef = ref(null)
const formRef = ref(null)
const loading = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const searchQuery = ref('')
const tableData = ref([])

// computed计算属性搜索后的表格数据
const filteredTableData = computed(() => {
  if (!searchQuery.value) {
    return tableData.value
  }
  return tableData.value.filter(item => 
    item.name.toLowerCase().includes(searchQuery.value.toLowerCase())
  )
})

// 表单数据
const form = ref({
  name: '',
  category: '',
  price: 0,
  stock: 0
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
  ],
  category: [
    { required: true, message: '请输入商品类别', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
  ],
  stock: [
    { required: true, message: '请输入商品库存', trigger: 'blur' },
  ]
}

// 获取商品列表
const fetchData = async () => {
  loading.value = true
  try {
    const res = await productStore.fetchProducts()
    tableData.value = res
  } catch (error) {
    console.error('获取商品列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearchClear = () => {
  searchQuery.value = ''
}

// 处理添加
const handleAdd = () => {
  isEdit.value = false
  form.value = {
    name: '',
    category: '',
    price: 0,
    stock: 0
  }
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row) => {
  isEdit.value = true
  form.value = { ...row }
  dialogVisible.value = true
}

// 处理删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除商品 "${row.name}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await productStore.deleteProduct(row.id)
    alertRef.value?.showAlert('删除商品成功')
    await fetchData()
  } catch (error) {
    if (error !== 'cancel') {  // 用户点击取消按钮不显示错误提示
      console.error('删除失败:', error)
      alertRef.value?.showAlert('删除商品失败', 'error')
    }
  }
}
// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (isEdit.value) {
          await productStore.updateProduct(form.value.id, form.value)
          alertRef.value?.showAlert('更新商品成功')
        } else {
          await productStore.addProduct(form.value)
          alertRef.value?.showAlert('添加商品成功')
        }
        dialogVisible.value = false
        await fetchData()
      } catch (error) {
        console.error(isEdit.value ? '更新失败:' : '添加失败:', error)
        alertRef.value?.showAlert(
            isEdit.value ? '更新商品失败' : '添加商品失败',
            'error'
        )
      }
    }
  })
}

onMounted(() => {
  fetchData()
})
</script>
<template>
  <div class="page-container">
    <el-card class="main-card">
      <!-- 搜索和添加区域 -->
      <div class="operation-area">
        <el-input
            v-model="searchQuery"
            placeholder="请输入商品名称搜索"
            style="width: 200px"
            clearable
            @clear="handleSearchClear"
        >
          <template #suffix>
            <el-icon class="el-input__icon" @click="handleSearch">
              <Search />
            </el-icon>
          </template>
        </el-input>

        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>添加商品
        </el-button>
      </div>

      <!-- 表格区域 -->
      <el-table :data="filteredTableData" border v-loading="loading">
        <el-table-column prop="name" label="商品名称" align="center" min-width="200" />
        <el-table-column prop="category" label="类别" align="center" width="120" />
        <el-table-column prop="price" label="价格" width="120" align="center">
          <template #default="{ row }">
            <span class="price-text">¥{{ row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="80" align="center">
          <template #default="{ row }">
            <span class="stock-text">{{ row.stock }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right" align="center">
          <template #default="{ row }">
            <div style="display: flex; align-items: center; justify-content: center">
              <el-button type="primary" link @click="handleEdit(row)">
                <el-icon><Edit /></el-icon>编辑
              </el-button>
              <el-divider direction="vertical" />
              <el-button type="danger" link @click="handleDelete(row)">
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加，编辑提示框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '编辑商品' : '添加商品'"
        width="500px"
    >
      <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="类别" prop="category">
          <el-input v-model="form.category" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number
              v-model="form.price"
              :min="0"
              :precision="2"
              :step="1"
          />
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input-number
              v-model="form.stock"
              :min="0"
              :precision="0"
          />
        </el-form-item>
      </el-form>
      <div style="display: flex; justify-content: flex-end; gap: 10px; margin-top: 20px;">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>

    <!-- 消息提示组件 -->
    <alert-notification ref="alertRef" />
  </div>
</template>
<style scoped>
.page-container {
  padding: 20px;
}

.operation-area {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price-text {
  color: #f56c6c;
}

.stock-text {
  color: #409eff;
}

.el-button {
  display: flex;
  align-items: center;
}

.el-icon {
  margin-right: 4px;
}

.el-dialog__footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-table__cell) {
  border-right: 1px solid #EBEEF5;
}

:deep(.el-table__cell:last-child) {
  border-right: none;
}

:deep(.el-table) {
  border: 1px solid #EBEEF5;
}
</style>